import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

export class SocketResponse {
  status: 'start'|'connection'|'end'|'error';
  data: any;
}

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {
  ws: WebSocket;
  isConnection = false;
  constructor() { }

  createObservableWebSocket(url): Observable<SocketResponse> {
    return new Observable(observer => {
      this.ws = new WebSocket(url);
      this.ws.onopen = () => {
        this.isConnection = true;
        observer.next({status: 'start', data: {}});
      };
      this.ws.onmessage = (event) => {
        this.isConnection = false;
        observer.next({
          status: 'connection',
          data: event.data
        })
      };
      this.ws.onerror = (event) => {
        this.isConnection = false;
        observer.next({
          status: 'error',
          data: {}
        })
      };
      this.ws.onclose = (event) => {
        this.isConnection = false;
        observer.next({
          status: 'end',
          data: {}
        });
        observer.complete();
      }
    })
  }

  //向服务器发送一个消息
	sendMessage(message: string) {
		this.ws.send(message);
  }

	//关闭连接  
	closeWebSocket() {
    this.isConnection = false;
		this.ws.close();
	}
}
